/**
 * @Description:
 * @author 紫霞
 * @since 2019/1/17
 */
// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Row, Col, Card, Button, Tabs, Form, Popconfirm, Modal, } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'

// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
//引用listPage
import ListPage from 'widget/PageTmpl/ListPage'
// 当前组件样式
import styles from './reportClientListStyle.less'
import { Grid, QueryCondition } from 'widget/Grid/index'
import { AdvanceSearch } from 'widget/CollapsiblePanels/index'
import Keypress  from 'widget/Keypress'
import { chunk } from 'lodash'

import classnames from 'classnames/bind';
let cx = classnames.bind(styles);

/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const TabPane = Tabs.TabPane
const routeView = function ({dispatch, model, form}) {
  // 表单的子函数
  const {resetFields, getFieldDecorator, validateFields, setFieldsValue} = form
  // 取出model对象，命名空间
  const {modelObj, namespace} = model
  let {loading, btnLoading, modalObj, currentItem, queryList, tableData, pageConfig,statisticsInfo} = modelObj
  // modelObj.xxx获取model中状态机的值
  console.log('modelObj', modelObj)
  // 点击处理事件
  const clickHandler = (e) => {
    // 分发到model文件中effects的xxx方法
    dispatch({
      type: `${namespace}/xxx`,
      payload: {}
    })
  }
  //（1：夫妻 2：子女 3：父母）
  let relationshipMap={
    1:'夫妻',
    2:'子女',
    3:'父母',
  }
  // 中介公司  经纪人  经纪人电话  报备客户姓名  报备客户电话 报备时间   报备客户状态
  const columns = [
    {title: '中介公司', dataIndex: 'orgName', key: 'orgName',},
    {title: '团队名称', dataIndex: 'teamName', key: 'teamName',},
    {title: '经纪人', dataIndex: 'referrerName', key: 'referrerName'},
    {title: '经纪人电话', dataIndex: 'referrerMobile', key: 'referrerMobile',width:130},
    {title: '报备客户姓名', dataIndex: 'custName', key: 'custName'},
    {title: '报备客户电话', dataIndex: 'custMobile', key: 'custMobile',width:130},
    {title: '报备项目', dataIndex: 'productName', key: 'productName'},
    {title: '报备时间', dataIndex: 'recommendTime', key: 'recommendTime',},
    {title: '报备客户状态', dataIndex: 'status', key: 'status',width:80 },
  ]
  // 表格模板配置
  const gridProps = {
    nameSpace: namespace,
    data: {
      columns: [].concat(columns, generateAction()),
      pageConfig, tableData
    },
    pageChange: (pageNo, pageSize) => {
      console.log(pageNo, pageSize)
      dispatch({ type: `${namespace}/pageChange`, payload: {pageNo, pageSize } });
    },
    scroll: {x: 800},
    loading
  }
  
  // 表格操作区域 备案列表  启用  停用
  function generateAction () {
    return {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 100,
      render: (data, item, index) => {
        return (
          <div>
            <span>
              <a onClick={() =>{
                updateModal({item,index})
              }}>查看</a>{<span className="ant-divider "/>}
            </span>
          </div>
        )
      }
    }
  }

  // 弹窗
  function updateModal ({item, index} = {}) {
    modalObj.visible = !modalObj.visible
    currentItem = item
    console.log('updateModal', item, index)
    changeState({modalObj})
    if (item) {
      dispatch({
        type: `${namespace}/getDetail`,
        payload: {...item,index}
      })
    }
  }
  
  // 详情
  function handleDetailList () {
    // 报备客户姓名 报备电话  报备楼盘 报备客户状态  关联人姓名 关联手机号码   与报备人关系  创建时间
    let list = []
    let keys = [
      {
        name: '报备客户姓名',
        value: currentItem['custName'] || '',
      },
      {
        name: '报备电话',
        value: currentItem['custMobile'] || '',
      },
      {
        name: '报备楼盘',
        value: currentItem['productName'] || '',
      },
      {
        name: '报备客户状态',
        value: currentItem['status'] || '',
      },
      {
        name: '关联人姓名',
        value: currentItem['relationshipName'] || '',
      },
      {
        name: '关联手机号码',
        value: currentItem['relationshipMobile'] || '',
      },
      {
        name: '与报备人关系',//（1：夫妻 2：子女 3：父母）
        value: relationshipMap[currentItem['relationship']] || '',
      },
      {
        name: '创建时间',
        value: currentItem['recommendTime'] || '',
      },
    ]

    list = chunk(keys, 2)
    currentItem.list = list
  }
  
  handleDetailList()
  
  //修改状态
  const changeState = (payload) => {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {...payload}
    })
  }
  //查询
  const onSearch = (payload) => {
    dispatch({
      type: `${namespace}/search`,
      payload: payload
    })
  }
  // 详情页跳转
  function routerGo ({url='', query={} }) {
    hashHistory.push({
      pathname: url,
      query: query
    })
  }
  
  return (
    <div className={cx('pageLayout')}>
      {/*监控键盘事件，自动刷新数据*/}
      <Keypress keyCode={13} cbk={()=>{
        onSearch();
      }} />
      
      <div className="public_listMain">
        <div className="functionButton">
          <Button type="primary" onClick={() =>{
            dispatch({
              type: `${namespace}/exportList`,
              payload: {}
            })
          }}>导出</Button>
        </div>
        <AdvanceSearch
          footer={
            <span>
                <Button type="primary" htmlType="submit" onClick={() => onSearch()} loading={modelObj.loading}>搜索</Button>
                <Button onClick={() => dispatch({ type: `${namespace}/queryReset` })}>重置</Button>
              </span>
          }>
          <QueryCondition
            data={queryList}
            inputChange={(key, value) => dispatch({type: `${namespace}/inputChange`, payload: {key, value}})}
          />
        </AdvanceSearch>
        {/* 表格区域 */}
        <div className="boxShadow">
          <Row className={'mgb1'}>
            <Col span={24}>
              <span className={'mgr2'}>公司名称：{statisticsInfo.orgName||''}</span>
              <span className={'mgr2'}>门店合作码：{statisticsInfo.cooperationCode||''}</span>
              <span className={'mgr2'}>团队成员：{statisticsInfo.memberCount||'0'}人</span>
              <span className={'mgr2'}> 报备客户：{statisticsInfo.recommendNum||'0'}人</span>
              <span className={'mgr2'}>已签约：{statisticsInfo.signedNum||'0'}人</span>
            </Col>
          </Row>
          
          {/* 添加用户 */}
          <Grid {...gridProps} />
        </div>
        <Modal
          title={'报备客户信息'}
          width='80%'
          // className="pubBiz_CommonModel"
          visible={modalObj.visible}
          onCancel={() => {updateModal({})}}
          footer={null}
        >
          <Row className={'mgb1'}>
            <Col span={24}>
              <span className={'mgr2'}>中介公司：{ statisticsInfo.orgName||''}</span>
              <span className={'mgr2'}>经纪人：{ currentItem.referrerName||''}</span>
            </Col>
          </Row>
          <div className={styles.detailContainer}>
            <table>
              <tbody className={'ant-table-tbody'}>
              {
                currentItem.list.map((item,idx) => {
                  let item_0 = item[0] || {}
                  let item_1 = item[1] || {}
                  return (
                    <tr key={idx}>
                      <td>{item_0.name}</td>
                      <td>{item_0.value}</td>
                      <td>{item_1.name}</td>
                      <td>{item_1.value}</td>
                    </tr>
                  )
                })
              }
              </tbody>
            </table>
          </div>
        </Modal>
      </div>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))

